package lnet

import (
	"errors"
	"fmt"
	"linx/liface"
	"sync"
)

type ConnManager struct {
	connections map[uint32]liface.IConnection
	connLock    sync.RWMutex
}

func NewConnManager() *ConnManager {
	return &ConnManager{
		connections: make(map[uint32]liface.IConnection),
	}
}

// 添加链接
func (c *ConnManager) Add(conn liface.IConnection) {
	// 加写锁
	c.connLock.Lock()
	defer c.connLock.Unlock()

	c.connections[conn.GetConnID()] = conn
	fmt.Println("ConnectionID", conn.GetConnID(), " add to ConnManager successfully: conn num = ", c.Len())
}

// 删除链接
func (c *ConnManager) Remove(conn liface.IConnection) {
	// 加写锁
	c.connLock.Lock()
	defer c.connLock.Unlock()

	delete(c.connections, conn.GetConnID())
	fmt.Println("ConnectionID", conn.GetConnID(), " remove to ConnManager successfully: conn num = ", c.Len())

}

// 根据connID 获取连接
func (c *ConnManager) Get(connID uint32) (liface.IConnection, error) {
	c.connLock.RLock()
	defer c.connLock.RUnlock()
	if conn, ok := c.connections[connID]; ok {
		return conn, nil
	}

	return nil, errors.New("Connection is not found!")
}

// 得到当前连接总数
func (c *ConnManager) Len() int {
	return len(c.connections)
}

// 清除all
func (c *ConnManager) ClearConn() {
	c.connLock.Lock()
	defer c.connLock.Unlock()

	// 删除并停止conn
	for connID, conn := range c.connections {
		// 停止
		conn.Stop()
		// 删除
		delete(c.connections, connID)
	}
	fmt.Println("Clear all connection succ!")
}
